// active-report-detail.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    reportId: '',
    reportInfo: null,
    reportImages: [],
    existingAuditImages: [], // 已上传的审核图片
    existingAuditVideos: [], // 已上传的审核视频
    newAuditImages: {}, // 新选择的审核图片（按产品编号分组）
    newAuditVideos: {}, // 新选择的审核视频（按产品编号分组）
    reportImageUrls: [],
    existingAuditImageUrls: [],
    submitting: false,
    uploadResults: [], // 上传结果
    // 权限相关数据
    hasAuditPermission: false
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/active-report-detail/active-report-detail')) {
      return
    }

    if (options.id) {
      this.setData({
        reportId: options.id
      })
      this.loadActiveReportDetail()
    }
  },

  // 加载主动报工详情
  loadActiveReportDetail() {
    api.getActiveReportDetail(this.data.reportId).then(res => {
      console.log('主动报工详情API返回数据:', res)
      
      const reportInfo = res.data.activeReport
      const productItemImages = res.data.productItemImages || []
      
      console.log('产品编号图片数据:', productItemImages)
      
      // 格式化时间
      reportInfo.createtime_text = this.formatTime(reportInfo.createtime)
      
      // 处理产品编号显示
      const itemNos = productItemImages.map(item => item.item_no).join(', ')
      
      // 初始化每个产品编号的审核图片和视频数组
      const newAuditImages = {}
      const newAuditVideos = {}
      productItemImages.forEach(item => {
        newAuditImages[item.item_no] = []
        newAuditVideos[item.item_no] = []
      })
      
      // 检查审核权限
      const hasAuditPermission = this.hasPermission('active_report_manage', 'audit')
      
      this.setData({
        reportInfo: reportInfo,
        productItemImages: productItemImages,
        itemNos: itemNos, // 添加处理后的产品编号字符串
        newAuditImages: newAuditImages, // 重置新选择的图片（按产品编号分组）
        newAuditVideos: newAuditVideos, // 重置新选择的视频（按产品编号分组）
        hasAuditPermission: hasAuditPermission
      })
      
      console.log('设置到页面的产品编号图片:', this.data.productItemImages)
      console.log('报工状态:', reportInfo.status)
      console.log('是否有审核权限:', this.hasPermission('active_report_manage', 'audit'))
      console.log('是否显示审核按钮:', reportInfo.status == 0 && this.hasPermission('active_report_manage', 'audit'))
    }).catch(err => {
      console.error('加载主动报工详情失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    const urls = e.currentTarget.dataset.urls
    
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  // 选择图片
  chooseAuditImage(e) {
    // 检查管理员登录状态
    const adminToken = wx.getStorageSync('adminToken')
    if (!adminToken) {
      wx.showModal({
        title: '提示',
        content: '请先登录管理员账号',
        showCancel: false,
        success: () => {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
      return
    }
    
    // 获取产品编号
    const itemNo = e.currentTarget.dataset.itemNo
    if (!itemNo) {
      wx.showToast({
        title: '请选择产品编号',
        icon: 'none'
      })
      return
    }
    
    // 初始化产品编号的审核图片数组
    if (!this.data.newAuditImages[itemNo]) {
      this.setData({
        [`newAuditImages.${itemNo}`]: []
      })
    }
    
    const currentImages = this.data.newAuditImages[itemNo] || []
    const remaining = 9 - currentImages.length
    if (remaining <= 0) {
      wx.showToast({
        title: '该产品编号最多只能上传9张图片',
        icon: 'none'
      })
      return
    }

    wx.chooseImage({
      count: remaining,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = currentImages.concat(res.tempFilePaths)
        this.setData({
          [`newAuditImages.${itemNo}`]: newImages
        })
      }
    })
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const itemNo = e.currentTarget.dataset.itemNo
    const newAuditImages = this.data.newAuditImages[itemNo] || []
    newAuditImages.splice(index, 1)
    this.setData({
      [`newAuditImages.${itemNo}`]: newAuditImages
    })
  },

  // 选择视频
  chooseAuditVideo(e) {
    // 检查管理员登录状态
    const adminToken = wx.getStorageSync('adminToken')
    if (!adminToken) {
      wx.showModal({
        title: '提示',
        content: '请先登录管理员账号',
        showCancel: false,
        success: () => {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
      return
    }
    
    // 获取产品编号
    const itemNo = e.currentTarget.dataset.itemNo
    if (!itemNo) {
      wx.showToast({
        title: '请选择产品编号',
        icon: 'none'
      })
      return
    }
    
    // 初始化产品编号的审核视频数组
    if (!this.data.newAuditVideos[itemNo]) {
      this.setData({
        [`newAuditVideos.${itemNo}`]: []
      })
    }
    
    const currentVideos = this.data.newAuditVideos[itemNo] || []
    const remaining = 5 - currentVideos.length
    if (remaining <= 0) {
      wx.showToast({
        title: '该产品编号最多只能上传5个视频',
        icon: 'none'
      })
      return
    }

    wx.chooseVideo({
      count: remaining,
      sourceType: ['album', 'camera'],
      maxDuration: 60, // 最大60秒（微信小程序限制）
      camera: 'back',
      compressed: true, // 压缩视频
      success: (res) => {
        console.log('选择视频成功:', res)
        
        // 检查视频大小（限制为50MB）
        const maxSize = 50 * 1024 * 1024 // 50MB
        if (res.size > maxSize) {
          wx.showToast({
            title: '视频文件过大，请选择小于50MB的视频',
            icon: 'none'
          })
          return
        }
        
        // 检查视频时长（限制为60秒）
        if (res.duration > 60) {
          wx.showToast({
            title: '视频时长过长，请选择60秒以内的视频',
            icon: 'none'
          })
          return
        }
        
        // 计算文件大小文本
        const sizeText = (res.size / 1024 / 1024).toFixed(1) + 'MB'
        
        const newVideos = currentVideos.concat({
          tempFilePath: res.tempFilePath,
          tempThumbPath: res.thumbTempFilePath,
          duration: Math.floor(res.duration),
          size: res.size,
          sizeText: sizeText,
          width: res.width,
          height: res.height
        })
        this.setData({
          [`newAuditVideos.${itemNo}`]: newVideos
        })
        
        wx.showToast({
          title: '视频添加成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('选择视频失败:', err)
        let errorMsg = '选择视频失败'
        
        // 根据错误类型显示不同的提示
        if (err.errMsg && err.errMsg.includes('DEMUXER_ERROR')) {
          errorMsg = '视频格式不支持，请选择MP4格式的视频'
        } else if (err.errMsg && err.errMsg.includes('maxDuration')) {
          errorMsg = '视频时长过长，请选择60秒以内的视频'
        } else if (err.errMsg && err.errMsg.includes('cancel')) {
          return // 用户取消，不显示提示
        }
        
        wx.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 删除视频
  deleteVideo(e) {
    const index = e.currentTarget.dataset.index
    const itemNo = e.currentTarget.dataset.itemNo
    const newAuditVideos = this.data.newAuditVideos[itemNo] || []
    newAuditVideos.splice(index, 1)
    this.setData({
      [`newAuditVideos.${itemNo}`]: newAuditVideos
    })
  },

  // 预览视频
  previewVideo(e) {
    const url = e.currentTarget.dataset.url
    // 如果是本地临时文件，直接播放
    if (url.startsWith('http://tmp/') || url.startsWith('wx://')) {
      wx.navigateTo({
        url: `/pages/video-player/video-player?url=${encodeURIComponent(url)}`
      })
    } else {
      // 如果是网络视频，直接播放
      wx.navigateTo({
        url: `/pages/video-player/video-player?url=${encodeURIComponent(url)}`
      })
    }
  },

  // 预览上传图片
  previewUploadImage(e) {
    const url = e.currentTarget.dataset.url
    const urls = e.currentTarget.dataset.urls
    
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  // 审核主动报工
  auditActiveReport(e) {
    const status = e.currentTarget.dataset.status
    let title = status == '1' ? '确认通过该主动报工？' : '确认拒绝该主动报工？'
    
    wx.showModal({
      title: '确认操作',
      content: title,
      success: (res) => {
        if (res.confirm) {
          this.submitAudit(status)
        }
      }
    })
  },

  // 提交审核
  submitAudit(status) {
    const data = {
      report_id: this.data.reportId,
      status: status
    }
    
    if (status == '2') {
      // 拒绝时需要输入原因
      wx.showModal({
        title: '拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因',
        success: (res) => {
          if (res.confirm) {
            data.audit_reason = res.content
            this.doSubmitAudit(data)
          }
        }
      })
    } else {
      this.doSubmitAudit(data)
    }
  },

  // 执行审核提交
  doSubmitAudit(data) {
    this.setData({ submitting: true })
    
    // 如果有图片或视频，先上传文件
    const hasImages = Object.keys(this.data.newAuditImages || {}).length > 0
    const hasVideos = Object.keys(this.data.newAuditVideos || {}).length > 0
    if (hasImages || hasVideos) {
      this.uploadAuditFiles(data)
    } else {
      this.submitAuditData(data)
    }
  },

  // 上传审核文件（图片和视频）
  uploadAuditFiles(data) {
    const images = this.data.newAuditImages || {}
    const videos = this.data.newAuditVideos || {}
    const uploadPromises = []
    const api = require('../../utils/api.js')
    
    // 上传图片 - 按产品编号分别上传
    Object.keys(images).forEach(itemNo => {
      const itemImages = images[itemNo] || []
      itemImages.forEach((imagePath, index) => {
        const promise = api.uploadActiveAuditImage(this.data.reportId, imagePath, itemNo)
        uploadPromises.push(promise)
      })
    })
    
    // 上传视频 - 按产品编号分别上传
    Object.keys(videos).forEach(itemNo => {
      const itemVideos = videos[itemNo] || []
      itemVideos.forEach((video, index) => {
        const promise = api.uploadActiveAuditVideo(this.data.reportId, video.tempFilePath, itemNo)
        uploadPromises.push(promise)
      })
    })
    
    Promise.all(uploadPromises).then((results) => {
      // 保存上传结果
      const uploadResults = results.map(res => ({
        url: res.data.url || res.data
      }))
      
      this.setData({
        uploadResults: uploadResults
      })
      
      this.submitAuditData(data)
    }).catch((err) => {
      this.setData({ submitting: false })
      wx.showToast({
        title: '文件上传失败',
        icon: 'none'
      })
    })
  },

  // 提交审核数据
  submitAuditData(data) {
    // 收集所有已上传的文件URL
    const allAuditImages = []
    const allAuditVideos = []
    
    // 从上传结果中收集文件URL
    if (this.data.uploadResults) {
      this.data.uploadResults.forEach(result => {
        if (result.url) {
          if (result.url.includes('.mp4')) {
            allAuditVideos.push(result.url)
          } else {
            allAuditImages.push(result.url)
          }
        }
      })
    }
    
    // 添加文件URL到审核数据
    data.audit_images = allAuditImages
    data.audit_videos = allAuditVideos
    
    console.log('提交审核数据:', data)
    
    api.auditActiveReport(data).then(res => {
      this.setData({ submitting: false })
      
      wx.showToast({
        title: '审核成功',
        icon: 'success'
      })
      
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }).catch(err => {
      this.setData({ submitting: false })
      console.error('审核失败:', err)
      wx.showToast({
        title: err.msg || '审核失败',
        icon: 'none'
      })
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 格式化产品编号，去掉前缀
  formatItemNo(itemNo) {
    if (!itemNo) return ''
    // 去掉前缀 "ORD2025072591AE49-3+F-扪皮-"
    const prefix = 'ORD2025072591AE49-3+F-扪皮-'
    if (itemNo.startsWith(prefix)) {
      return itemNo.substring(prefix.length)
    }
    return itemNo
  },

  // 权限检查方法
  hasPermission(module, action) {
    const app = getApp()
    const adminInfo = app.globalData.adminInfo
    if (!adminInfo || !adminInfo.id) {
      return false
    }
    return permissionUtils.hasPermission(adminInfo.id, module, action)
  },

  // 显示权限不足提示
  showPermissionDenied(module, action) {
    const description = permissionUtils.getPermissionDescription(module, action)
    wx.showModal({
      title: '权限不足',
      content: `您没有${description}的权限`,
      showCancel: false,
      success: () => {
        wx.navigateBack()
      }
    })
  }
})
